package ReflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2022-07-20
 * Time: 14:03
 */
public class reflectClassDemo {
    /**
     * 反射获取对象
     */
    public static void reflectNewInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> c1=Class.forName("ReflectDemo.Student");
        Student student=(Student)c1.newInstance();

        System.out.println(student);
        student.sleep();
    }

    /**
     * 通过反射，调用构造方法【公有、私有都有】
     */
    public static void reflectPrivateConstruct() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c=Class.forName("ReflectDemo.Student");
        Constructor<?> constructor=c.getDeclaredConstructor(int.class,String.class,int.class);
        //设置true后可以修改访问权限
        constructor.setAccessible(true);
        Student student=(Student)constructor.newInstance(22222,"qian",13);
        System.out.println(student);
    }
    /**
     * 通过反射，调用属性【公有、私有都有】
     */
    public static  void reflectPrivateField() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> c=Class.forName("ReflectDemo.Student");
        Student student=(Student)c.newInstance();
        Field field=c.getDeclaredField("name");
        field.setAccessible(true);
        field.set(student,"a");
        System.out.println(student);
    }
    /**
     * 通过反射，调用方法【公有、私有都有】
     */
    public static void reflectPrivateMethod() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> c=Class.forName("ReflectDemo.Student");
        Student student=(Student) c.newInstance();
        Method method=c.getDeclaredMethod("eat",String.class);
        method.setAccessible(true);
        method.invoke(student,"cat");
    }
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        reflectNewInstance();
        reflectPrivateConstruct();
        reflectPrivateField();
        reflectPrivateMethod();
    }
}
